package org.redmagic.client.location;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.redmagic.api.RedMagicRequestFactory;
import org.redmagic.api.RedMagicResponse;
import org.redmagic.client.api.RedMagicTransaction;

public class WebLocation extends AbstractLocation {

	private static final Log LOG = LogFactory.getLog(WebLocation.class);
	
	private List<List<String>> hierarchy;
	
	private final RedMagicRequestFactory requestFactory;
	
	private final RedMagicTransaction transaction;
	
	WebLocation(String name, URI uri, RedMagicRequestFactory requestFactory, RedMagicTransaction transaction) {
		super(name, uri);
		this.requestFactory = requestFactory;
		this.transaction = transaction;
		this.hierarchy = new ArrayList<List<String>>();
	}
	
	public List<List<String>> getHierarchy() {
		return hierarchy;
	}
	
	@Override
	public Properties resolvePlaceholders(Set<String> placeholders) {

		RedMagicResponse response = transaction.execute(this.getUri(), 
					                                    requestFactory.createRequest(hierarchy, placeholders),
					                                    requestFactory.getMediaType());
		
		return response.unmarshall();
	}
	
	@Override
	public void finished(Properties resolvedProperties) {
		requestFactory.shutdown();
	}
	
	protected void addAttempt(List<String> attempt) {
		hierarchy.add(attempt);
	}
	
	@Override
	public String toString() {
		return (this.getName() == null ? "WebLocation" : this.getName()) + " [" + this.getUri() + "]";
	}
}
